package com.jdjw.modules.migranttasksign.controller;


import com.alibaba.fastjson.JSON;
import com.jdjw.common.ResponseResult;
import com.jdjw.modules.migranttasksign.entity.MigrantTaskSign;
import com.jdjw.modules.migranttasksign.entity.MigrantTaskSignCommit;
import com.jdjw.modules.migranttasksign.entity.MigrantTaskSignSave;
import com.jdjw.modules.migranttasksign.entity.MigrantTaskSignVo;
import com.jdjw.modules.migranttasksign.service.MigrantTaskSignService;
import com.jdjw.modules.migrantworkssign.entity.MigrantWorksSign;
import com.jdjw.modules.migrantworkssign.service.MigrantWorksSignService;
import com.jdjw.modules.sysuser.entity.SysUser;
import com.jdjw.modules.sysuser.service.SysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 务工发布表 前端控制器
 * </p>
 *
 * @author fq
 * @since 2021-07-28
 */
@RestController
@RequestMapping("/migranttasksign")
public class MigrantTaskSignController {

    @Autowired
    private MigrantTaskSignService migrantTaskSignService;

    @Autowired
    private MigrantWorksSignService migrantWorksSignService;

    @Autowired
    private SysUserService sysUserService;

    @ApiOperation("务工发布-查询")
    @PostMapping("queryAll")
    public ResponseResult queryAll(MigrantTaskSignVo migrantTaskSignVo){
        return migrantTaskSignService.queryAll(migrantTaskSignVo);
    }

    @ApiOperation("务工发布查询-查询")
    @PostMapping("queryAllList")
    public ResponseResult queryAllList(MigrantTaskSignVo migrantTaskSignVo){
        return migrantTaskSignService.queryAllList(migrantTaskSignVo);
    }

    @ApiOperation("务工发布查询-指派务工人员查询")
    @PostMapping("getMigrantTypePersonList")
    @ResponseBody
    public ResponseResult getMigrantTypePersonList(String id,String porvetyType,String permissions,String orgId,String deptId){
        ResponseResult rrt=new ResponseResult();
        try {
            MigrantTaskSign migrantTaskSign = migrantTaskSignService.getById(id);
            String zs = migrantTaskSign.getAttribute01();
            String hb = migrantTaskSign.getAttribute02();
            int count = Integer.valueOf(zs) + Integer.valueOf(hb);

            //根据务工类型查询务工人员信息
            Map<String, Object> map = new HashMap<>();
            if (permissions.equals("1")) {
                map.put("orgId", orgId);
            } else if (permissions.equals("2")) {
                map.put("deptId", deptId);
            }
            map.put("migrantType", migrantTaskSign.getMigrantType());
            List<Map<String, Object>> migrantTypePersonList = new ArrayList<>();
            if ("0".equals(porvetyType)) {
                map.put("isPorvety", "是");
                int count1 =migrantWorksSignService.queryPersonCount(map);
                if (count1 < count) {
                    map.put("isPorvety", "0");
                    migrantTypePersonList =migrantWorksSignService.queryPersonInfo(map);
                } else {
                    map.put("isPorvety", "1");
                    migrantTypePersonList =migrantWorksSignService.queryPersonInfo(map);
                }
            } else {
                migrantTypePersonList =migrantWorksSignService.queryPersonInfo(map);
            }
            rrt.setMsg("指派务工人员查询成功");
            rrt.setCode(200);
            rrt.setData(migrantTypePersonList);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            rrt.setMsg("指派务工人员查询异常"+e.getMessage());
            rrt.setCode(500);
            rrt.setData(null);
        }
        return rrt;
    }

    /**
     *
     * @param userId 用户id
     * @param orgName 机构名称
     * @param deptName 部门名称
     * @param workId 务工发布id
     * @param officialMigrantPersonListString 正式务工人员选择
     * @param waitMigrantPersonListString   候补务工人员选择
     * @param porvetyType 务工人员模式：0 戴农富模式 1直接指派模式
     * @return
     */
    @ApiOperation("务工发布查询-指派务工人员添加")
    @PostMapping("insertmigrantpersonforworks")
    public ResponseResult insertmigrantpersonforworks(String userId,String orgName,String deptName,String workId, String officialMigrantPersonListString, String waitMigrantPersonListString, String porvetyType){
        ResponseResult rrt=new ResponseResult();
        SysUser user = sysUserService.getById(userId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            String[] arr = officialMigrantPersonListString.split(",");
            if (!waitMigrantPersonListString.equals("")) {
                String[] array = waitMigrantPersonListString.split(",");
                //修改人员状态
                migrantWorksSignService.updateWorkerInfoById(array);
                //添加关联信息
                for (int i = 0; i < array.length; i++) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", UUID.randomUUID().toString().replace("-", ""));
                    map.put("taskCode", workId);
                    map.put("workerCode", array[i]);
                    map.put("isMigrantOfficial", "2");
                    map.put("orgId", user.getOrgId());
                    map.put("orgName", orgName);
                    map.put("deptId", user.getDeptId());
                    map.put("deptName", deptName);
                    map.put("createDate", sdf.format(new Date()));
                    map.put("createBy", user.getId());
                    map.put("updateDate", null);
                    map.put("updateBy", null);
                    map.put("attribute01", null);
                    map.put("attribute02", null);
                    map.put("attribute03", null);
                    map.put("attribute04", null);
                    map.put("attribute05", null);
                    map.put("attribute06", null);
                    map.put("attribute07", null);
                    map.put("attribute08", null);
                    map.put("attribute09", null);
                    map.put("attribute10", null);
                    map.put("attribute11", null);
                    map.put("attribute12", null);
                    map.put("attribute13", null);
                    map.put("attribute14", null);
                    map.put("attribute15", null);
                    migrantTaskSignService.insertMigrantTaskWorkerInfo(map);
                }
            }
            //修改人员状态
            migrantWorksSignService.updateWorkerInfoById(arr);
            //添加关联信息
            for (int j = 0; j < arr.length; j++) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", UUID.randomUUID().toString().replace("-", ""));
                map.put("taskCode", workId);
                map.put("workerCode", arr[j]);
                map.put("isMigrantOfficial", "1");
                map.put("orgId", user.getOrgId());
                map.put("orgName", orgName);
                map.put("deptId", user.getDeptId());
                map.put("deptName", deptName);
                map.put("createDate", sdf.format(new Date()));
                map.put("createBy", user.getId());
                map.put("updateDate", null);
                map.put("updateBy", null);
                map.put("attribute01", null);
                map.put("attribute02", null);
                map.put("attribute03", null);
                map.put("attribute04", null);
                map.put("attribute05", null);
                map.put("attribute06", null);
                map.put("attribute07", null);
                map.put("attribute08", null);
                map.put("attribute09", null);
                map.put("attribute10", null);
                map.put("attribute11", null);
                map.put("attribute12", null);
                map.put("attribute13", null);
                map.put("attribute14", null);
                map.put("attribute15", null);
                this.migrantTaskSignService.insertMigrantTaskWorkerInfo(map);
            }
            //修改务工状态为已经添加过人员
            Map<String, Object> param = new HashMap<>();
            param.put("id", workId);
            if ("0".equals(porvetyType)) {
                param.put("modeltype", "带农富模式（选择困难群众务工）");
            } else if ("1".equals(porvetyType)) {
                param.put("modeltype", "其它选择务工人员模式");
            } else {
                param.put("modeltype", "摇号选择务工人员模式");
            }
            migrantWorksSignService.updateWorksIsCompleteInfo(param);
            rrt.setCode(200);
            rrt.setMsg("添加成功");
        } catch (Exception e) {
            rrt.setCode(500);
            rrt.setMsg("添加异常"+e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return rrt;
    }

    @ApiOperation("务工发布查询-务工结算查看")
    @PostMapping("{id}/finishMigrant")
    public ResponseResult finishMigrant(@PathVariable("id")String id){
        ResponseResult rrt=new ResponseResult();
        try {

            MigrantTaskSign migrantTaskSign = migrantTaskSignService.getById(id);
            //根据务工信息id查询该工作务工人员信息
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            List<Map<String, Object>> infoList = migrantTaskSignService.queryMigrantInfoByTaskId(map);
            for (int i = 0; i < infoList.size(); i++) {
                Map<String, Object> stringObjectMap = infoList.get(i);
                String worker_sex = (String)stringObjectMap.get("workerSexFont");
                if("女".equals(worker_sex)){
                    stringObjectMap.put("ruleUnitPrice", stringObjectMap.get("migrantLadyPrice"));
                }else{
                    stringObjectMap.put("ruleUnitPrice", stringObjectMap.get("migrantUnitPrice"));
                }
            }
            migrantTaskSign.setLists(infoList);
            rrt.setCode(200);
            rrt.setMsg("结算查看成功");
            rrt.setData(migrantTaskSign);
        } catch (Exception e) {
            rrt.setCode(500);
            rrt.setMsg("结算查看异常"+e.getMessage());
            rrt.setData(null);
            e.printStackTrace();
        }
        return rrt;
    }


    @ApiOperation("务工发布-发布务工")
    @PostMapping("save")
    public ResponseResult queryAll(MigrantTaskSignSave migrantTaskSignSave){
        ResponseResult rrt=new ResponseResult();
        try {
            MigrantTaskSign gts=new MigrantTaskSign();
            //转换
            BeanUtils.copyProperties(migrantTaskSignSave,gts);
            gts.setIdApproval("0");
            //随机务工编码
            gts.setMigrantCode(UUID.randomUUID().toString().replaceAll("-",""));
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            //获取当前时间
            gts.setCreateDate(sdf.format(new Date()));
            migrantTaskSignService.save(gts);
            rrt.setCode(200);
            rrt.setMsg("保存成功");
        } catch (BeansException e) {
            e.printStackTrace();
            rrt.setCode(500);
            rrt.setMsg("保存失败"+e.getMessage());
        }
        return rrt;
    }

    @ApiOperation("务工发布-修改")
    @PostMapping("edit")
    public ResponseResult edit(@RequestBody String sqlEdit) throws JSONException {
        JSONObject json=new JSONObject(sqlEdit);
        return migrantTaskSignService.edit(json.getString("sqlEdit"));
    }

    @ApiOperation("务工发布-审批")
    @PostMapping("commit")
    public ResponseResult commit(MigrantTaskSignCommit migrantTaskSignCommit){
        ResponseResult rrt=new ResponseResult();
        try {
            MigrantTaskSign migranrTaskSign = migrantTaskSignService.getById(migrantTaskSignCommit.getId());
            migranrTaskSign.setIdApproval(migrantTaskSignCommit.getIdApproval());
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(!StringUtils.isEmpty(migrantTaskSignCommit.getAttribute03())){//判断是否是村委审核
                migranrTaskSign.setAttribute03(migrantTaskSignCommit.getAttribute03());
                migranrTaskSign.setAttribute04(sdf.format(new Date()));
            }else{//村书记审核
                migranrTaskSign.setAttribute05(migrantTaskSignCommit.getAttribute05());
                migranrTaskSign.setAttribute06(sdf.format(new Date()));
            }
            migrantTaskSignService.updateById(migranrTaskSign);
            rrt.setMsg("审核成功");
            rrt.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            rrt.setMsg("审核失败"+e.getMessage());
            rrt.setCode(500);
        }
        return rrt;
    }


    @ApiOperation("务工发布-查看")
    @PostMapping("{id}/preview")
    public ResponseResult preview(@PathVariable("id")String id){
        ResponseResult rrt=new ResponseResult();
        try {
            MigrantTaskSign byId = migrantTaskSignService.getById(id);
            rrt.setCode(200);
            rrt.setMsg("查看成功");
            rrt.setData(byId);
        } catch (Exception e) {
            e.printStackTrace();
            rrt.setCode(500);
            rrt.setMsg("查看失败"+e.getMessage());
            rrt.setData(null);
        }

        return rrt;
    }


}

